package com.briup.smartcity_group1.web.mapping;

import com.briup.smartcity_group1.utils.mapping.IPackageURIPrefix;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/** 自定义映射
 * @author congee(congee02 @ 163.com)
 * @date 1/3/2023 12:31 PM
 */
public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    protected Set<IPackageURIPrefix> iPackageURIPrefixes;
    protected boolean hasPackageURIPrefix = false;

    @Override
    public void afterPropertiesSet() {
        initVersionHandlers();
        super.afterPropertiesSet();
    }

    @Override
    protected void initHandlerMethods() {
        super.initHandlerMethods();
    }

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo info = super.getMappingForMethod(method, handlerType);
        if (info != null) {
            final String packageName = handlerType.getPackage().getName();
            for (IPackageURIPrefix iPackageURIPrefix : iPackageURIPrefixes) {
                if (packageName.startsWith(iPackageURIPrefix.getPackageName())) {
                    RequestMappingInfo packageUriInfo = buildRequestMappingInfo(iPackageURIPrefix.getPrefix());
                    info = packageUriInfo.combine(info);
                    return info;
                }
            }
        }
        return info;
    }

    protected void initVersionHandlers() {
        iPackageURIPrefixes = new HashSet<>(obtainApplicationContext().getBeansOfType(IPackageURIPrefix.class).values());
        hasPackageURIPrefix = ! CollectionUtils.isEmpty(iPackageURIPrefixes);
    }

    protected RequestMappingInfo buildRequestMappingInfo(String path) {
        return RequestMappingInfo.paths(path).build();
    }

}
